# named pipe Client
# encoding: utf-8

import os
import json
import sys

prog = sys.argv[0]
input = sys.argv[1]
output = sys.argv[2]

write_path = "/tmp/server_in.pipe"
read_path = "/tmp/server_out.pipe"

f = os.open(write_path, os.O_SYNC | os.O_CREAT | os.O_RDWR)
#print "Client open f", f

rf = None

# Client发送请求
fin = open(input, "r")
fout = open(output, "w")

req_data = json.loads(fin.read())
fin.close()

'''
req_data = "example_data.json"
with open(req_data, "r") as read_file:
    xx = json.load(read_file)

    xxx = json.dumps(xx)
'''

len_send = os.write(f, req_data + '\0')
print "request", len_send

if rf == None:
    # *要点1：在这里第一次打开read_path，实际这里的open是一个阻塞操作
    # 打开的时机很重要。如果在程序刚开始，没发送请求就打开read_path，肯定会阻塞住
    rf = os.open(read_path, os.O_RDONLY)
    #print "client opened rf", rf

# 接收Server回应
received_response = ''
while True:
    s = os.read(rf, 1024)  # 20
    received_response = received_response + s

    # Reach the end
    if s[len(s)-1] == '\0':
        break

#if len(s) == 0:
    # 一般来说，是管道被意外关闭了，比如Server退出了
#    break

print "received", received_response
fout.write(json.dumps(received_response))

fout.close()

os.close(f)
os.close(rf)
